#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
常量同步脚本

自动读取 client/assets/battle/Const.ts 文件中的常量值，
并同步更新 creeps_server/static/api 目录下各语言的 const 文件。
"""

import os
import re
import json
from typing import Dict, Any, List, Tuple
from pathlib import Path


class ConstantSyncer:
    """常量同步器"""
    
    def __init__(self, source_file: str, target_dir: str):
        self.source_file = Path(source_file)
        self.target_dir = Path(target_dir)
        self.constants = {}
        self.configs = {}
        self.config_comments = {}
        
    def parse_typescript_constants(self) -> Dict[str, Any]:
        """解析 TypeScript 常量文件"""
        print(f"正在解析源文件: {self.source_file}")
        
        with open(self.source_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 解析基础常量
        self._parse_basic_constants(content)
        
        # 解析配置对象
        self._parse_config_objects(content)
        
        return {
            'constants': self.constants,
            'configs': self.configs
        }
    
    def _parse_basic_constants(self, content: str):
        """解析基础常量"""
        # 匹配 export const CONSTANT_NAME = value; 格式
        patterns = {
            'RoundLimit': r'export\s+const\s+RoundLimit\s*=\s*(\d+)',
            'CommandFailLimit': r'export\s+const\s+CommandFailLimit\s*=\s*(\d+)',
            'InitRMB': r'export\s+const\s+InitRMB\s*=\s*(\d+)',
            'SplashDamageRatio': r'export\s+const\s+SplashDamageRatio\s*=\s*([\d.]+)',
        }
        
        for name, pattern in patterns.items():
            match = re.search(pattern, content)
            if match:
                value = match.group(1)
                # 转换为适当的类型
                if '.' in value:
                    self.constants[name] = float(value)
                else:
                    self.constants[name] = int(value)
                print(f"  找到常量: {name} = {self.constants[name]}")
        
        # 解析 DirectionType 对象
        self._parse_direction_type(content)
    
    def _parse_direction_type(self, content: str):
        """解析 DirectionType 对象"""
        # 匹配 DirectionType 对象定义
        direction_pattern = r'export\s+const\s+DirectionType\s*=\s*\{([^}]+)\}'
        match = re.search(direction_pattern, content, re.DOTALL)
        
        if match:
            direction_content = match.group(1)
            directions = {}
            
            # 解析每个方向的定义
            direction_entries = re.findall(r'(\w+):\s*\[([^\]]+)\]', direction_content)
            for name, coords in direction_entries:
                # 解析坐标数组
                coord_values = [int(x.strip()) for x in coords.split(',')]
                directions[name] = coord_values
            
            self.constants['DirectionType'] = directions
            print(f"  找到 DirectionType: {directions}")
    
    def _parse_config_objects(self, content: str):
        """解析配置对象"""
        # 解析 UnitConfig
        self._parse_unit_config(content)
        
        # 解析 ResourceConfig  
        self._parse_resource_config(content)
        
        # 解析 BuildingConfig
        self._parse_building_config(content)
    
    def _parse_unit_config(self, content: str):
        """解析单位配置"""
        # 匹配 UnitConfig 对象
        pattern = r'export\s+const\s+UnitConfig\s*=\s*\{(.*?)\};'
        match = re.search(pattern, content, re.DOTALL)
        
        if match:
            config_content = match.group(1)
            result = self._parse_config_entries(config_content, 'UnitType')
            self.configs['UnitConfig'] = result
            print(f"  解析到 UnitConfig: {len(self.configs['UnitConfig'])} 个单位")
    
    def _parse_resource_config(self, content: str):
        """解析资源配置"""
        pattern = r'export\s+const\s+ResourceConfig\s*=\s*\{(.*?)\};'
        match = re.search(pattern, content, re.DOTALL)
        
        if match:
            config_content = match.group(1)
            self.configs['ResourceConfig'] = self._parse_config_entries(config_content, 'TildeType')
            print(f"  解析到 ResourceConfig: {len(self.configs['ResourceConfig'])} 个资源")
    
    def _parse_building_config(self, content: str):
        """解析建筑配置"""
        pattern = r'export\s+const\s+BuildingConfig\s*=\s*\{(.*?)\};'
        match = re.search(pattern, content, re.DOTALL)
        
        if match:
            config_content = match.group(1)
            self.configs['BuildingConfig'] = self._parse_config_entries(config_content, 'BuildingType')
            print(f"  解析到 BuildingConfig: {len(self.configs['BuildingConfig'])} 个建筑")
    
    def _parse_config_entries(self, config_content: str, enum_type: str) -> Dict[str, Dict[str, Any]]:
        """解析配置条目"""
        entries = {}
        
        # 匹配每个配置条目 [EnumType.key]: { ... }
        pattern = rf'\[{enum_type}\.(\w+)\]:\s*\{{(.*?)\}}'
        matches = re.finditer(pattern, config_content, re.DOTALL)
        
        for match in matches:
            key = match.group(1)
            entry_content = match.group(2)
            
            # 解析条目内的属性和注释
            entry = {}
            entry_comments = {}
            
            # 匹配属性和注释: /** 注释 */ \n property: value,
            # 先匹配所有的注释和属性对
            comment_prop_pattern = r'/\*\*\s*([^*]+?)\s*\*/\s*\n?\s*(\w+):\s*([^,\n]+)'
            comment_matches = re.finditer(comment_prop_pattern, entry_content)
            
            for comment_match in comment_matches:
                comment_text = comment_match.group(1).strip()
                prop_name = comment_match.group(2)
                prop_value_str = comment_match.group(3).strip().rstrip(',')
                
                # 解析属性值
                if prop_value_str.startswith('"') or prop_value_str.startswith("'"):
                    # 字符串值
                    prop_value = prop_value_str.strip('"\'')
                    entry[prop_name] = prop_value
                else:
                    # 数值
                    try:
                        prop_value = int(prop_value_str)
                        entry[prop_name] = prop_value
                    except ValueError:
                        entry[prop_name] = prop_value_str
                
                # 保存注释
                entry_comments[prop_name] = comment_text
            
            entries[key] = entry
            # 将注释信息也保存到配置中
            if not hasattr(self, 'config_comments'):
                self.config_comments = {}
            if enum_type not in self.config_comments:
                self.config_comments[enum_type] = {}
            self.config_comments[enum_type][key] = entry_comments
        
        return entries
    
    def generate_javascript_file(self, target_file: str):
        """生成 JavaScript 常量文件"""
        print(f"正在生成 JavaScript 文件: {target_file}")
        
        lines = [
            "/**",
            " * 常量定义模块",
            " *",
            " * 包含游戏中所有的枚举类型、配置数据和工具函数",
            " */",
            "",
            "// 常量定义",
        ]
        
        # 添加基础常量
        const_mapping = {
            'RoundLimit': 'ROUND_LIMIT',
            'CommandFailLimit': 'COMMAND_FAIL_LIMIT', 
            'InitRMB': 'INIT_RMB',
            'SplashDamageRatio': 'SPLASH_DAMAGE_RATIO'
        }
        
        for ts_name, js_name in const_mapping.items():
            if ts_name in self.constants:
                value = self.constants[ts_name]
                comment = self._get_constant_comment(ts_name)
                lines.append(f"const {js_name} = {value};{comment}")
        
        lines.extend([
            "",
            "// 枚举定义",
            "const UnitType = {",
            "    soldier: 0,    // 士兵",
            "    collect: 1,    // 采集兵", 
            "    doctor: 2,     // 治疗兵",
            "    archer: 3,     // 弓箭手",
            "    worker: 4      // 建造兵",
            "};",
            "",
            "const TildeType = {",
            "    flat: 0,     // 平地",
            "    hill: 1,     // 山丘",
            "    river: 2,    // 河流",
            "    gold: 11,    // 黄金矿",
            "    energy: 12,  // 能源矿",
            "    wood: 13,    // 木材",
            "    stone: 14    // 石材",
            "};",
            "",
            "const BuildingType = {",
            "    base: 0,   // 基地",
            "    tower: 1,  // 防御塔",
            "    wall: 2    // 城墙",
            "};",
            "",
            "const EntityType = {",
            "    unit: 0,     // 单位",
            "    building: 1, // 建筑",
            "    terrain: 2   // 地形",
            "};",
            "",
            "const DirectionType = {",
            "    up: [0, -1],     // 向上",
            "    down: [0, 1],    // 向下",
            "    left: [-1, 0],   // 向左",
            "    right: [1, 0]    // 向右",
            "};",
            "",
            "const CommandType = {",
            "    init: \"init\",       // 初始化战场",
            "    end: \"end\",         // 结束",
            "    move: \"move\",       // 移动",
            "    attack: \"attack\",   // 攻击",
            "    build: \"build\",     // 建造",
            "    swap: \"swap\",       // 生产",
            "    heal: \"heal\",       // 治疗",
            "    collect: \"collect\"  // 采集",
            "};",
            "",
            "const PlayerType = {",
            "    PLAYER1: \"player1\",  // 玩家1",
            "    PLAYER2: \"player2\",  // 玩家2",
            "    ADMIN: \"admin\"       // 管理员",
            "};",
            "",
        ])
        
        # 添加配置对象
        if 'UnitConfig' in self.configs:
            lines.append("// 单位配置")
            lines.append("const UNIT_CONFIG = {")
            for unit_type, config in self.configs['UnitConfig'].items():
                lines.append(f"    [UnitType.{unit_type}]: {{")
                for prop, value in config.items():
                    # 使用解析到的具体注释，如果没有则使用通用注释
                    if (hasattr(self, 'config_comments') and 
                        'UnitType' in self.config_comments and 
                        unit_type in self.config_comments['UnitType'] and 
                        prop in self.config_comments['UnitType'][unit_type]):
                        comment_text = self.config_comments['UnitType'][unit_type][prop]
                        comment = f"           // {comment_text}"
                    else:
                        comment = self._get_property_comment(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        {prop}: \"{value}\",{comment}")
                    else:
                        lines.append(f"        {prop}: {value},{comment}")
                lines.append("    },")
            lines.append("};")
            lines.append("")
        
        if 'ResourceConfig' in self.configs:
            lines.append("// 资源配置")
            lines.append("const RESOURCE_CONFIG = {")
            for resource_type, config in self.configs['ResourceConfig'].items():
                lines.append(f"    [TildeType.{resource_type}]: {{")
                for prop, value in config.items():
                    # 使用解析到的具体注释，如果没有则使用通用注释
                    if (hasattr(self, 'config_comments') and 
                        'TildeType' in self.config_comments and 
                        resource_type in self.config_comments['TildeType'] and 
                        prop in self.config_comments['TildeType'][resource_type]):
                        comment_text = self.config_comments['TildeType'][resource_type][prop]
                        comment = f"           // {comment_text}"
                    else:
                        comment = self._get_property_comment(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        {prop}: \"{value}\",{comment}")
                    else:
                        lines.append(f"        {prop}: {value},{comment}")
                lines.append("    },")
            lines.append("};")
            lines.append("")
        
        if 'BuildingConfig' in self.configs:
            lines.append("// 建筑配置")
            lines.append("const BUILDING_CONFIG = {")
            for building_type, config in self.configs['BuildingConfig'].items():
                lines.append(f"    [BuildingType.{building_type}]: {{")
                for prop, value in config.items():
                    # 使用解析到的具体注释，如果没有则使用通用注释
                    if (hasattr(self, 'config_comments') and 
                        'BuildingType' in self.config_comments and 
                        building_type in self.config_comments['BuildingType'] and 
                        prop in self.config_comments['BuildingType'][building_type]):
                        comment_text = self.config_comments['BuildingType'][building_type][prop]
                        comment = f"           // {comment_text}"
                    else:
                        comment = self._get_property_comment(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        {prop}: \"{value}\",{comment}")
                    else:
                        lines.append(f"        {prop}: {value},{comment}")
                lines.append("    },")
            lines.append("};")
            lines.append("")
        
        # 添加工具函数和导出
        lines.extend([
            "// 工具函数",
            "function getUnitConfig(unitType) {",
            "    return UNIT_CONFIG[unitType];",
            "}",
            "",
            "function getBuildingConfig(buildingType) {",
            "    return BUILDING_CONFIG[buildingType];",
            "}",
            "",
            "function getResourceConfig(resourceType) {",
            "    return RESOURCE_CONFIG[resourceType];",
            "}",
            "",
            "function isResourceTildeType(tildeType) {",
            "    return (",
            "        tildeType === TildeType.gold ||",
            "        tildeType === TildeType.energy ||",
            "        tildeType === TildeType.wood ||",
            "        tildeType === TildeType.stone",
            "    );",
            "}",
            "",
            "module.exports = {",
            "    // 常量",
            "    ROUND_LIMIT,",
            "    COMMAND_FAIL_LIMIT,",
            "    INIT_RMB,",
            "    SPLASH_DAMAGE_RATIO,",
            "",
            "    // 枚举",
            "    UnitType,",
            "    TildeType,",
            "    BuildingType,",
            "    EntityType,",
            "    DirectionType,",
            "    CommandType,",
            "    PlayerType,",
            "",
            "    // 配置",
            "    UNIT_CONFIG,",
            "    RESOURCE_CONFIG,",
            "    BUILDING_CONFIG,",
            "",
            "    // 工具函数",
            "    getUnitConfig,",
            "    getBuildingConfig,",
            "    getResourceConfig,",
            "    isResourceTildeType",
            "};",
        ])
        
        # 写入文件
        with open(target_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(lines))
    
    def generate_python_file(self, target_file: str):
        """生成 Python 常量文件"""
        print(f"正在生成 Python 文件: {target_file}")
        
        lines = [
            "# -*- coding: utf-8 -*-",
            "\"\"\"常量定义模块",
            "",
            "包含游戏中所有的枚举类型、配置数据和工具函数",
            "\"\"\"",
            "",
            "from enum import IntEnum",
            "from typing import Any, Dict",
            "",
            "# 常量定义",
        ]
        
        # 添加基础常量
        const_mapping = {
            'RoundLimit': 'ROUND_LIMIT',
            'CommandFailLimit': 'COMMAND_FAIL_LIMIT',
            'InitRMB': 'INIT_RMB', 
            'SplashDamageRatio': 'SPLASH_DAMAGE_RATIO'
        }
        
        for ts_name, py_name in const_mapping.items():
            if ts_name in self.constants:
                value = self.constants[ts_name]
                comment = self._get_constant_comment_python(ts_name)
                lines.append(f"{py_name} = {value}{comment}")
        
        lines.extend([
            "",
            "",
            "# 枚举定义",
            "class UnitType(IntEnum):",
            "    \"\"\"单位类型枚举\"\"\"",
            "",
            "    soldier = 0  # 士兵",
            "    collect = 1  # 采集兵",
            "    doctor = 2  # 治疗兵",
            "    archer = 3  # 弓箭手",
            "    worker = 4  # 建造兵",
            "",
            "",
            "class TildeType(IntEnum):",
            "    \"\"\"地块类型枚举\"\"\"",
            "",
            "    flat = 0  # 平地",
            "    hill = 1  # 山丘",
            "    river = 2  # 河流",
            "    gold = 11  # 黄金矿",
            "    energy = 12  # 能源矿",
            "    wood = 13  # 木材",
            "    stone = 14  # 石材",
            "",
            "",
            "class BuildingType(IntEnum):",
            "    \"\"\"建筑类型枚举\"\"\"",
            "",
            "    base = 0  # 基地",
            "    tower = 1  # 防御塔",
            "    wall = 2  # 城墙",
            "",
            "",
            "class EntityType(IntEnum):",
            "    \"\"\"实体类型枚举\"\"\"",
            "",
            "    unit = 0  # 单位",
            "    building = 1  # 建筑",
            "    terrain = 2  # 地形",
            "",
            "",
            "class CommandType:",
            "    \"\"\"命令类型常量\"\"\"",
            "",
            "    init = 'init'  # 初始化战场",
            "    end = 'end'  # 结束",
            "    move = 'move'  # 移动",
            "    attack = 'attack'  # 攻击",
            "    build = 'build'  # 建造",
            "    swap = 'swap'  # 生产",
            "    heal = 'heal'  # 治疗",
            "    collect = 'collect'  # 采集",
            "",
            "",
            "class PlayerType:",
            "    \"\"\"玩家类型常量\"\"\"",
            "",
            "    PLAYER1 = 'player1'  # 玩家1",
            "    PLAYER2 = 'player2'  # 玩家2",
            "    ADMIN = 'admin'  # 管理员",
            "",
            "",
        ])
        
        # 生成 DirectionType 类
        if 'DirectionType' in self.constants:
            directions = self.constants['DirectionType']
            lines.extend([
                "class DirectionType:",
                "    \"\"\"方向类型常量\"\"\"",
                "",
            ])
            
            for direction, coords in directions.items():
                comment = f"  # 向{self._get_direction_comment(direction)}"
                lines.append(f"    {direction} = {coords}{comment}")
            
            lines.extend([
                "",
                "",
            ])
        else:
            # 如果没有解析到 DirectionType，使用默认值
            lines.extend([
                "class DirectionType:",
                "    \"\"\"方向类型常量\"\"\"",
                "",
                "    up = [0, -1]  # 向上",
                "    down = [0, 1]  # 向下",
                "    left = [-1, 0]  # 向左",
                "    right = [1, 0]  # 向右",
                "",
                "",
            ])
        
        lines.extend([
        ])
        
        # 添加配置对象
        if 'UnitConfig' in self.configs:
            lines.append("# 单位配置")
            lines.append("UNIT_CONFIG = {")
            for unit_type, config in self.configs['UnitConfig'].items():
                lines.append(f"    UnitType.{unit_type}: {{")
                for prop, value in config.items():
                    # 使用解析到的具体注释，如果没有则使用通用注释
                    if (hasattr(self, 'config_comments') and 
                        'UnitType' in self.config_comments and 
                        unit_type in self.config_comments['UnitType'] and 
                        prop in self.config_comments['UnitType'][unit_type]):
                        comment_text = self.config_comments['UnitType'][unit_type][prop]
                        comment = f"          # {comment_text}"
                    else:
                        comment = self._get_property_comment_python(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        '{prop}': '{value}',{comment}")
                    else:
                        lines.append(f"        '{prop}': {value},{comment}")
                lines.append("    },")
            lines.append("}")
            lines.append("")
        
        if 'ResourceConfig' in self.configs:
            lines.append("# 资源配置")
            lines.append("RESOURCE_CONFIG = {")
            for resource_type, config in self.configs['ResourceConfig'].items():
                lines.append(f"    TildeType.{resource_type}: {{")
                # 按照正确顺序输出属性：name -> value -> icon
                prop_order = ['name', 'value', 'icon']
                for prop in prop_order:
                    if prop in config:
                        value = config[prop]
                        # 使用解析到的具体注释，如果没有则使用通用注释
                        if (hasattr(self, 'config_comments') and 
                            'TildeType' in self.config_comments and 
                            resource_type in self.config_comments['TildeType'] and 
                            prop in self.config_comments['TildeType'][resource_type]):
                            comment_text = self.config_comments['TildeType'][resource_type][prop]
                            comment = f"          # {comment_text}"
                        else:
                            comment = self._get_property_comment_python(prop)
                        
                        if isinstance(value, str):
                            lines.append(f"        '{prop}': '{value}',{comment}")
                        else:
                            lines.append(f"        '{prop}': {value},{comment}")
                lines.append("    },")
            lines.append("}")
            lines.append("")
        
        if 'BuildingConfig' in self.configs:
            lines.append("# 建筑配置")
            lines.append("BUILDING_CONFIG = {")
            for building_type, config in self.configs['BuildingConfig'].items():
                lines.append(f"    BuildingType.{building_type}: {{")
                for prop, value in config.items():
                    # 使用解析到的具体注释，如果没有则使用通用注释
                    if (hasattr(self, 'config_comments') and 
                        'BuildingType' in self.config_comments and 
                        building_type in self.config_comments['BuildingType'] and 
                        prop in self.config_comments['BuildingType'][building_type]):
                        comment_text = self.config_comments['BuildingType'][building_type][prop]
                        comment = f"          # {comment_text}"
                    else:
                        comment = self._get_property_comment_python(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        '{prop}': '{value}',{comment}")
                    else:
                        lines.append(f"        '{prop}': {value},{comment}")
                lines.append("    },")
            lines.append("}")
            lines.append("")
        
        # 添加工具函数
        lines.extend([
            "# 工具函数",
            "def get_unit_config(unit_type: UnitType) -> Dict[str, Any]:",
            "    \"\"\"获取单位配置\"\"\"",
            "    return UNIT_CONFIG.get(unit_type, {})",
            "",
            "",
            "def get_building_config(building_type: BuildingType) -> Dict[str, Any]:",
            "    \"\"\"获取建筑配置\"\"\"",
            "    return BUILDING_CONFIG.get(building_type, {})",
            "",
            "",
            "def get_resource_config(resource_type: TildeType) -> Dict[str, Any]:",
            "    \"\"\"获取资源配置\"\"\"",
            "    return RESOURCE_CONFIG.get(resource_type, {})",
            "",
            "",
            "def is_resource_tilde_type(tilde_type: TildeType) -> bool:",
            "    \"\"\"判断地块类型是否为资源地形\"\"\"",
            "    return tilde_type in [",
            "        TildeType.gold,",
            "        TildeType.energy,",
            "        TildeType.wood,",
            "        TildeType.stone",
            "    ]",
        ])
        
        # 写入文件
        with open(target_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(lines))
    
    def generate_lua_file(self, target_file: str):
        """生成 Lua 常量文件"""
        print(f"正在生成 Lua 文件: {target_file}")
        
        lines = [
            "-- -*- coding: utf-8 -*-",
            "-- 常量定义模块",
            "-- 包含游戏中所有的枚举类型、配置数据和工具函数",
            "",
            "local const = {}",
            "",
            "-- 常量定义",
        ]
        
        # 添加基础常量
        const_mapping = {
            'RoundLimit': 'ROUND_LIMIT',
            'CommandFailLimit': 'COMMAND_FAIL_LIMIT',
            'InitRMB': 'INIT_RMB',
            'SplashDamageRatio': 'SPLASH_DAMAGE_RATIO'
        }
        
        for ts_name, lua_name in const_mapping.items():
            if ts_name in self.constants:
                value = self.constants[ts_name]
                comment = self._get_constant_comment_lua(ts_name)
                lines.append(f"const.{lua_name} = {value}{comment}")
        
        lines.extend([
            "",
            "-- 枚举定义",
            "const.UnitType = {",
            "    soldier = 0,  -- 士兵",
            "    collect = 1,  -- 采集兵",
            "    doctor = 2,   -- 治疗兵",
            "    archer = 3,   -- 弓箭手",
            "    worker = 4    -- 建造兵",
            "}",
            "",
            "const.TildeType = {",
            "    flat = 0,     -- 平地",
            "    hill = 1,     -- 山丘",
            "    river = 2,    -- 河流",
            "    gold = 11,    -- 黄金矿",
            "    energy = 12,  -- 能源矿",
            "    wood = 13,    -- 木材",
            "    stone = 14    -- 石材",
            "}",
            "",
            "const.BuildingType = {",
            "    base = 0,   -- 基地",
            "    tower = 1,  -- 防御塔",
            "    wall = 2    -- 城墙",
            "}",
            "",
            "const.EntityType = {",
            "    unit = 0,     -- 单位",
            "    building = 1, -- 建筑",
            "    terrain = 2   -- 地形",
            "}",
            "",
            "const.DirectionType = {",
            "    up = {0, -1},     -- 向上",
            "    down = {0, 1},    -- 向下",
            "    left = {-1, 0},   -- 向左",
            "    right = {1, 0}    -- 向右",
            "}",
            "",
            "const.CommandType = {",
            "    init = \"init\",       -- 初始化战场",
            "    [\"end\"] = \"end\",         -- 结束",
            "    move = \"move\",       -- 移动",
            "    attack = \"attack\",   -- 攻击",
            "    build = \"build\",     -- 建造",
            "    swap = \"swap\",       -- 生产",
            "    heal = \"heal\",       -- 治疗",
            "    collect = \"collect\"  -- 采集",
            "}",
            "",
            "const.PlayerType = {",
            "    PLAYER1 = \"player1\",  -- 玩家1",
            "    PLAYER2 = \"player2\",  -- 玩家2",
            "    ADMIN = \"admin\"       -- 管理员",
            "}",
            "",
        ])
        
        # 添加配置对象
        if 'UnitConfig' in self.configs:
            lines.append("-- 单位配置")
            lines.append("const.UNIT_CONFIG = {")
            for unit_type, config in self.configs['UnitConfig'].items():
                lines.append(f"    [const.UnitType.{unit_type}] = {{")
                for prop, value in config.items():
                    # 优先使用具体注释，如果没有则使用通用注释
                    specific_comment = None
                    if hasattr(self, 'config_comments') and 'UnitType' in self.config_comments:
                        if unit_type in self.config_comments['UnitType']:
                            specific_comment = self.config_comments['UnitType'][unit_type].get(prop)

                    
                    if specific_comment:
                        comment = f" -- {specific_comment}"
                    else:
                        comment = self._get_property_comment_lua(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        {prop} = \"{value}\",{comment}")
                    else:
                        lines.append(f"        {prop} = {value},{comment}")
                lines.append("    },")
            lines.append("}")
            lines.append("")
        
        if 'ResourceConfig' in self.configs:
            lines.append("-- 资源配置")
            lines.append("const.RESOURCE_CONFIG = {")
            for resource_type, config in self.configs['ResourceConfig'].items():
                lines.append(f"    [const.TildeType.{resource_type}] = {{")
                for prop, value in config.items():
                    # 优先使用具体注释，如果没有则使用通用注释
                    specific_comment = None
                    if hasattr(self, 'config_comments') and 'TildeType' in self.config_comments:
                        if resource_type in self.config_comments['TildeType']:
                            specific_comment = self.config_comments['TildeType'][resource_type].get(prop)
                    
                    if specific_comment:
                        comment = f" -- {specific_comment}"
                    else:
                        comment = self._get_property_comment_lua(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        {prop} = \"{value}\",{comment}")
                    else:
                        lines.append(f"        {prop} = {value},{comment}")
                lines.append("    },")
            lines.append("}")
            lines.append("")
        
        if 'BuildingConfig' in self.configs:
            lines.append("-- 建筑配置")
            lines.append("const.BUILDING_CONFIG = {")
            for building_type, config in self.configs['BuildingConfig'].items():
                lines.append(f"    [const.BuildingType.{building_type}] = {{")
                for prop, value in config.items():
                    # 优先使用具体注释，如果没有则使用通用注释
                    specific_comment = None
                    if hasattr(self, 'config_comments') and 'BuildingType' in self.config_comments:
                        if building_type in self.config_comments['BuildingType']:
                            specific_comment = self.config_comments['BuildingType'][building_type].get(prop)
                    
                    if specific_comment:
                        comment = f" -- {specific_comment}"
                    else:
                        comment = self._get_property_comment_lua(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        {prop} = \"{value}\",{comment}")
                    else:
                        lines.append(f"        {prop} = {value},{comment}")
                lines.append("    },")
            lines.append("}")
            lines.append("")
        
        # 添加工具函数
        lines.extend([
            "-- 工具函数",
            "function const.get_unit_config(unit_type)",
            "    return const.UNIT_CONFIG[unit_type]",
            "end",
            "",
            "function const.get_building_config(building_type)",
            "    return const.BUILDING_CONFIG[building_type]",
            "end",
            "",
            "function const.get_resource_config(resource_type)",
            "    return const.RESOURCE_CONFIG[resource_type]",
            "end",
            "",
            "function const.is_resource_tilde_type(tilde_type)",
            "    return (",
            "        tilde_type == const.TildeType.gold or",
            "        tilde_type == const.TildeType.energy or",
            "        tilde_type == const.TildeType.wood or",
            "        tilde_type == const.TildeType.stone",
            "    )",
            "end",
            "",
            "return const",
        ])
        
        # 写入文件
        with open(target_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(lines))
    
    def generate_typescript_file(self, target_file: str):
        """生成 TypeScript 常量文件"""
        print(f"正在生成 TypeScript 文件: {target_file}")
        
        lines = [
            "/**",
            " * 常量定义模块",
            " *",
            " * 包含游戏中所有的枚举类型、配置数据和工具函数",
            " */",
            "",
            "// 常量定义",
        ]
        
        # 添加基础常量
        const_mapping = {
            'RoundLimit': 'ROUND_LIMIT',
            'CommandFailLimit': 'COMMAND_FAIL_LIMIT',
            'InitRMB': 'INIT_RMB',
            'SplashDamageRatio': 'SPLASH_DAMAGE_RATIO'
        }
        
        for ts_name, target_name in const_mapping.items():
            if ts_name in self.constants:
                value = self.constants[ts_name]
                comment = self._get_constant_comment(ts_name)
                lines.append(f"export const {target_name} = {value};{comment}")
        
        lines.extend([
            "",
            "// 枚举定义",
            "export enum UnitType {",
            "    soldier = 0,    // 士兵",
            "    collect = 1,    // 采集兵",
            "    doctor = 2,     // 治疗兵",
            "    archer = 3,     // 弓箭手",
            "    worker = 4      // 建造兵",
            "}",
            "",
            "export enum TildeType {",
            "    flat = 0,     // 平地",
            "    hill = 1,     // 山丘",
            "    river = 2,    // 河流",
            "    gold = 11,    // 黄金矿",
            "    energy = 12,  // 能源矿",
            "    wood = 13,    // 木材",
            "    stone = 14    // 石材",
            "}",
            "",
            "export enum BuildingType {",
            "    base = 0,   // 基地",
            "    tower = 1,  // 防御塔",
            "    wall = 2    // 城墙",
            "}",
            "",
            "export enum EntityType {",
            "    unit = 0,     // 单位",
            "    building = 1, // 建筑",
            "    terrain = 2   // 地形",
            "}",
            "",
            "export const DirectionType = {",
            "    up: [0, -1] as [number, number],     // 向上",
            "    down: [0, 1] as [number, number],    // 向下",
            "    left: [-1, 0] as [number, number],   // 向左",
            "    right: [1, 0] as [number, number]    // 向右",
            "} as const;",
            "",
            "export enum CommandType {",
            "    init = \"init\",       // 初始化战场",
            "    end = \"end\",         // 结束",
            "    move = \"move\",       // 移动",
            "    attack = \"attack\",   // 攻击",
            "    build = \"build\",     // 建造",
            "    swap = \"swap\",       // 生产",
            "    heal = \"heal\",       // 治疗",
            "    collect = \"collect\"  // 采集",
            "}",
            "",
            "export enum PlayerType {",
            "    PLAYER1 = \"player1\",  // 玩家1",
            "    PLAYER2 = \"player2\",  // 玩家2",
            "    ADMIN = \"admin\"       // 管理员",
            "}",
            "",
            "// 接口定义",
            "interface UnitConfig {",
            "    name: string;          // 名字",
            "    attack: number;        // 攻击力",
            "    speed: number;         // 移动速度",
            "    hp: number;            // 初始血量",
            "    attackRange: number;   // 攻击范围",
            "    cost: number;          // 生产成本",
            "    killedAward: number;   // 被击杀奖励",
            "    icon: string;          // 文本小图标",
            "}",
            "",
            "interface ResourceConfig {",
            "    name: string;          // 名字",
            "    value: number;         // 价值",
            "    icon: string;          // 文本小图标",
            "}",
            "",
            "interface BuildingConfig {",
            "    name: string;          // 名字",
            "    attack: number;        // 攻击力",
            "    hp: number;            // 初始血量",
            "    attackRange: number;   // 攻击范围",
            "    cost: number;          // 建造成本",
            "    killedAward: number;   // 被击杀奖励",
            "    icon: string;          // 文本小图标",
            "}",
            "",
        ])
        
        # 添加配置对象
        if 'UnitConfig' in self.configs:
            lines.append("// 单位配置")
            lines.append("export const UNIT_CONFIG: Record<UnitType, UnitConfig> = {")
            for unit_type, config in self.configs['UnitConfig'].items():
                lines.append(f"    [UnitType.{unit_type}]: {{")
                for prop, value in config.items():
                    # 优先使用具体注释，如果没有则使用通用注释
                    specific_comment = None
                    if hasattr(self, 'config_comments') and 'UnitType' in self.config_comments:
                        if unit_type in self.config_comments['UnitType']:
                            specific_comment = self.config_comments['UnitType'][unit_type].get(prop)
                    
                    if specific_comment:
                        comment = f" // {specific_comment}"
                    else:
                        comment = self._get_property_comment(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        {prop}: \"{value}\",{comment}")
                    else:
                        lines.append(f"        {prop}: {value},{comment}")
                lines.append("    },")
            lines.append("};")
            lines.append("")
        
        if 'ResourceConfig' in self.configs:
            lines.append("// 资源配置")
            lines.append("export const RESOURCE_CONFIG: Record<TildeType, ResourceConfig> = {")
            for resource_type, config in self.configs['ResourceConfig'].items():
                lines.append(f"    [TildeType.{resource_type}]: {{")
                for prop, value in config.items():
                    # 优先使用具体注释，如果没有则使用通用注释
                    specific_comment = None
                    if hasattr(self, 'config_comments') and 'TildeType' in self.config_comments:
                        if resource_type in self.config_comments['TildeType']:
                            specific_comment = self.config_comments['TildeType'][resource_type].get(prop)
                    
                    if specific_comment:
                        comment = f" // {specific_comment}"
                    else:
                        comment = self._get_property_comment(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        {prop}: \"{value}\",{comment}")
                    else:
                        lines.append(f"        {prop}: {value},{comment}")
                lines.append("    },")
            lines.append("} as any;")
            lines.append("")
        
        if 'BuildingConfig' in self.configs:
            lines.append("// 建筑配置")
            lines.append("export const BUILDING_CONFIG: Record<BuildingType, BuildingConfig> = {")
            for building_type, config in self.configs['BuildingConfig'].items():
                lines.append(f"    [BuildingType.{building_type}]: {{")
                for prop, value in config.items():
                    # 优先使用具体注释，如果没有则使用通用注释
                    specific_comment = None
                    if hasattr(self, 'config_comments') and 'BuildingType' in self.config_comments:
                        if building_type in self.config_comments['BuildingType']:
                            specific_comment = self.config_comments['BuildingType'][building_type].get(prop)
                    
                    if specific_comment:
                        comment = f" // {specific_comment}"
                    else:
                        comment = self._get_property_comment(prop)
                    
                    if isinstance(value, str):
                        lines.append(f"        {prop}: \"{value}\",{comment}")
                    else:
                        lines.append(f"        {prop}: {value},{comment}")
                lines.append("    },")
            lines.append("};")
            lines.append("")
        
        # 添加工具函数
        lines.extend([
            "// 工具函数",
            "export function getUnitConfig(unitType: UnitType): UnitConfig {",
            "    return UNIT_CONFIG[unitType];",
            "}",
            "",
            "export function getBuildingConfig(buildingType: BuildingType): BuildingConfig {",
            "    return BUILDING_CONFIG[buildingType];",
            "}",
            "",
            "export function getResourceConfig(resourceType: TildeType): ResourceConfig {",
            "    return RESOURCE_CONFIG[resourceType];",
            "}",
            "",
            "export function isResourceTildeType(tildeType: TildeType): boolean {",
            "    return (",
            "        tildeType === TildeType.gold ||",
            "        tildeType === TildeType.energy ||",
            "        tildeType === TildeType.wood ||",
            "        tildeType === TildeType.stone",
            "    );",
            "}",
            "",
            "// 接口导出",
            "export interface Position {",
            "    x: number;",
            "    y: number;",
            "}",
            "",
            "export interface Unit {",
            "    id: number;",
            "    type: UnitType;",
            "    playerId: number;",
            "    x: number;",
            "    y: number;",
            "    health: number;",
            "    maxHealth: number;",
            "}",
            "",
            "export interface Building {",
            "    id: number;",
            "    type: BuildingType;",
            "    playerId: number;",
            "    x: number;",
            "    y: number;",
            "    health: number;",
            "    maxHealth: number;",
            "}",
            "",
            "export interface Tile {",
            "    type: TildeType;",
            "    x?: number;",
            "    y?: number;",
            "}",
            "",
            "export interface GameMap {",
            "    width: number;",
            "    height: number;",
            "    terrain?: Tile[][];",
            "    tiles?: Tile[];",
            "}",
        ])
        
        # 写入文件
        with open(target_file, 'w', encoding='utf-8') as f:
            f.write('\n'.join(lines))
    
    def _get_constant_comment(self, const_name: str) -> str:
        """获取常量注释"""
        comments = {
            'RoundLimit': '            // 回合数上限',
            'CommandFailLimit': '     // 命令失败次数上限',
            'InitRMB': '              // 玩家初始经济',
            'SplashDamageRatio': '  // 溅射伤害比例'
        }
        return comments.get(const_name, '')
    
    def _get_constant_comment_python(self, const_name: str) -> str:
        """获取 Python 常量注释"""
        comments = {
            'RoundLimit': '  # 回合数上限',
            'CommandFailLimit': '  # 命令失败次数上限',
            'InitRMB': '  # 玩家初始经济',
            'SplashDamageRatio': '  # 溅射伤害比例'
        }
        return comments.get(const_name, '')
    
    def _get_constant_comment_lua(self, const_name: str) -> str:
        """获取 Lua 常量注释"""
        comments = {
            'RoundLimit': '            -- 回合数上限',
            'CommandFailLimit': '     -- 命令失败次数上限',
            'InitRMB': '              -- 玩家初始经济',
            'SplashDamageRatio': '  -- 溅射伤害比例'
        }
        return comments.get(const_name, '')
    
    def _get_property_comment(self, prop_name: str) -> str:
        """获取属性注释"""
        comments = {
            'name': '          // 名字',
            'attack': '           // 攻击力',
            'speed': '             // 移动速度',
            'hp': '               // 初始血量',
            'attackRange': '       // 攻击范围',
            'cost': '             // 生产成本',
            'killedAward': '      // 被击杀奖励',
            'icon': '            // 文本小图标',
            'value': '            // 价值'
        }
        return comments.get(prop_name, '')
    
    def _get_property_comment_python(self, prop_name: str) -> str:
        """获取 Python 属性注释"""
        comments = {
            'name': '          # 名字',
            'attack': '           # 攻击力',
            'speed': '             # 移动速度',
            'hp': '               # 初始血量',
            'attackRange': '       # 攻击范围',
            'cost': '             # 生产成本',
            'killedAward': '      # 被击杀奖励',
            'icon': '            # 文本小图标',
            'value': '            # 价值'
        }
        return comments.get(prop_name, '')
    
    def _get_property_comment_lua(self, prop_name: str) -> str:
        """获取 Lua 属性注释"""
        comments = {
            'name': '          -- 名字',
            'attack': '           -- 攻击力',
            'speed': '             -- 移动速度',
            'hp': '               -- 初始血量',
            'attackRange': '       -- 攻击范围',
            'cost': '             -- 生产成本',
            'killedAward': '      -- 被击杀奖励',
            'icon': '            -- 文本小图标',
            'value': '            -- 价值'
        }
        return comments.get(prop_name, '')
    
    def _get_direction_comment(self, direction: str) -> str:
        """获取方向的中文注释"""
        direction_map = {
            'up': '上',
            'down': '下',
            'left': '左',
            'right': '右'
        }
        return direction_map.get(direction, direction)
    
    def sync_all_files(self):
        """同步所有语言的常量文件"""
        print("开始同步常量文件...")
        
        # 解析源文件
        self.parse_typescript_constants()
        
        # 生成各语言文件
        target_files = {
            'js': self.target_dir / 'js' / 'api' / 'const.js',
            'py': self.target_dir / 'py' / 'api' / 'const.py',
            'lua': self.target_dir / 'lua' / 'api' / 'const.lua',
            'ts': self.target_dir / 'ts' / 'api' / 'const.ts',
        }
        
        # 确保目标目录存在
        for file_path in target_files.values():
            file_path.parent.mkdir(parents=True, exist_ok=True)
        
        # 生成文件
        self.generate_javascript_file(str(target_files['js']))
        self.generate_python_file(str(target_files['py']))
        self.generate_lua_file(str(target_files['lua']))
        self.generate_typescript_file(str(target_files['ts']))
        
        print("同步完成！")


def main():
    """主函数"""
    # 配置路径
    source_file = r"f:\trae_workspace\creeps_battle\client\assets\battle\Const.ts"
    target_dir = r"f:\trae_workspace\creeps_battle\creeps_server\static\api"
    
    # 创建同步器并执行同步
    syncer = ConstantSyncer(source_file, target_dir)
    syncer.sync_all_files()


if __name__ == "__main__":
    main()